package com.mtw.bbs.bbsUser.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.mtw.bbs.bbsUser.pojo.entity.RoleMenu;
import org.springframework.stereotype.Service;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import com.mtw.bbs.bbsUser.mapper.RoleMenuMapper;
import com.mtw.bbs.bbsUser.pojo.entity.RoleMenu;
import com.mtw.bbs.bbsUser.service.RoleMenuService;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.util.Collection;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * 角色菜单逻辑层
 * @author mo
 * @email mo
 * @date 2023-10-23 10:15:12
 */
@Service("roleMenuService")
public class RoleMenuServiceImpl extends ServiceImpl<RoleMenuMapper, RoleMenu> implements RoleMenuService {

    /**
     * 批量给角色添加菜单
     *
     * @param roleId      角色id
     * @param resourceIds 菜单id列表
     * @return 是否操作成功
     */
    @Override
    @Transactional
    public boolean saveBatch(String roleId, Collection<String> resourceIds) {
        if (CollectionUtils.isEmpty(resourceIds))
            return false;
        removeByRoleId(roleId);
        Set<RoleMenu> userRoles = resourceIds.stream().map(resourceId -> new RoleMenu(resourceId,roleId)).collect(Collectors.toSet());
        return saveBatch(userRoles);
    }


    /**
     * 删除角色拥有的菜单
     *
     * @param roleId 角色id
     * @return 是否操作成功
     */
    @Override
    @Transactional
    public boolean removeByRoleId(String roleId) {
        LambdaQueryWrapper<RoleMenu> lqw = new LambdaQueryWrapper<>();
        lqw.eq(RoleMenu::getRoleId, roleId);
        return remove(lqw);
    }


    /**
     * 删除角色集合拥有的菜单
     *
     * @param roleIds 角色id集合
     * @return 是否操作成功
     */
    @Override
    @Transactional
    public boolean removeByRoleIds(Collection<String> roleIds) {
        if (CollectionUtils.isEmpty(roleIds)){
            return false;
        }
        LambdaQueryWrapper<RoleMenu> lqw = new LambdaQueryWrapper<>();
        lqw.in(RoleMenu::getRoleId, roleIds);
        return remove(lqw);
    }


    /**
     * 查询角色拥有菜单id
     *
     * @param roleId 角色id
     * @return 角色拥有的菜单id集合
     */
    @Override
    public Set<String> queryByRoleId(String roleId) {

        LambdaQueryWrapper<RoleMenu> lqw = new LambdaQueryWrapper<>();
        lqw.eq(RoleMenu::getRoleId, roleId);
        List<RoleMenu> userRoleList = list(lqw);
        return userRoleList.stream().map(RoleMenu::getMenuId).collect(Collectors.toSet());
    }


    /**
     * 根据角色id列表查询菜单关系
     *
     * @param roleIds 角色id集合
     * @return 角色菜单关系集合
     */
    @Override
    public List<RoleMenu> queryByRoleIds(Collection<String> roleIds) {
        LambdaQueryWrapper<RoleMenu> lqw = new LambdaQueryWrapper<>();
        lqw.in(RoleMenu::getRoleId, roleIds);
        return this.list(lqw);
    }

}
